import { MyResponseType } from '@/types'
import axios, { AxiosRequestConfig } from 'axios'

const instance = axios.create({
  baseURL: '/api'
})

export const post = async (url: string, data = {}) => {
  const response = await instance.post(url, data)
  return response.data
}

export const get = async (url: string, params = {}) => {
  const response = await instance.get(url, {
    params
  })
  return response.data
}

const request = async <T = any>(config: AxiosRequestConfig): Promise<MyResponseType<T>> => {
  try {
    const { data } = await instance.request<MyResponseType<T>>(config)
    // data.code === 0
    //   ? console.log(data.message) // 成功消息提示
    //   : console.error(data.message) // 失败消息提示
    return data
  } catch (err) {
    const message = err.message || '请求失败'
    // console.log(message) // 失败消息提示
    return {
      code: -1,
      message,
      data: null as any
    }
  }
}

export default request
